import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { HeroService } from '../../services/hero.service';
import { StorageService } from '../../services/storage.service';

import {
  FormBuilder,
  FormGroup,
  Validators
} from '@angular/forms';


@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  nzSpin:boolean=false;
  validateForm: FormGroup;

  public errorTips:string;
  public codeUrl:string;
  public randomNum:number;

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[ i ].markAsDirty();
      this.validateForm.controls[ i ].updateValueAndValidity();
    }
  }

  constructor(private heroService: HeroService,
              private storageService: StorageService,
              private fb: FormBuilder,
              private router: Router) {
                this.randomNum=Math.random();
                this.codeUrl=host+"/code?key="+this.randomNum; 
              }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      username: [ null, [ Validators.required ] ],
      password: [ null, [ Validators.required ] ],
      captcha : [ null, [ Validators.required ] ],
      remember: [ true ]
    });
    //判断是否记住密码
    const getUsername = this.getExpire('username');
    const getPassword = this.getExpire('password');
    // console.log(getUsername,getPassword);
    if(getUsername && getPassword){
      this.validateForm.get('username').setValue(getUsername);
      this.validateForm.get('password').setValue(getPassword);
    }
  }

  changeCode(){
    this.randomNum=Math.random();
    this.codeUrl=host+"/code?key="+this.randomNum; 
  }

  loginIn() {
    if(this.validateForm.status=="VALID"){
      this.nzSpin=true;
      this.validateForm.value.picKey=this.randomNum; 
      let url=host+"/main/login/check";
      let model='username='+this.validateForm.value.username+'&password='+this.validateForm.value.password+'&picCode='+this.validateForm.value.captcha+'&picKey='+this.randomNum;
      this.heroService.post(url,model).then(result=>{
          // console.log(result);
          if(result.code==0){
            this.storageService.setItem('token',result.data); 
            if(this.validateForm.value.remember){
              const expiretime = 604800000;//1000*60*60*24*7
              this.setExpire('username',this.validateForm.value.username,expiretime);
              this.setExpire('password',this.validateForm.value.password,expiretime);
            }else{
              localStorage.removeItem('username');
              localStorage.removeItem('password');
            }
            this.router.navigate(['/main']);
          }else if(result.code==602){
            this.nzSpin=false;
            this.errorTips=result.msg;
            this.changeCode();
          }else{
            this.nzSpin=false;
            this.errorTips=result.msg;
            this.changeCode();
          }
      })
    }
  }

  cancelErrorTips(){
    this.errorTips="";
  }
  //localstorage 设置过期时间
  setExpire(key, value, expire){
    let obj = {
      data: value,
      time: Date.now(),
      expire: expire
    };
    //localStorage 设置的值不能为对象,转为json字符串
    localStorage.setItem(key, JSON.stringify(obj));
  }

  getExpire(key){
      let val = JSON.parse(localStorage.getItem(key));
      if (!val) {
          return false;
      }
      if (Date.now() - val.time > val.expire) {
          localStorage.removeItem(key);
          return null;
      }
      return val.data;
  }
}